package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");  //得到请求发过来的用户名
        String password = req.getParameter("password");   //得到请求发过来的密码
        if(username==null||username.length()==0||password==null||password.length()==0){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("你输入的用户名或密码为空");
            return;
        }
        //然后就查询一下数据库中是否存在用户输入的用户名和密码，是否匹配
        UserDao userDao = new UserDao();
        try {
            User user = userDao.getUserByName(username);
            if(user==null){
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("用户名不存在");
                return;
            }
            if(!password.equals(user.getPassword())){
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("输入的密码错误");
                return;
            }
            HttpSession session = req.getSession(true); //创建会话
            session.setAttribute("user",user);
            //跳转到主页

            resp.sendRedirect("blog_list.html");

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //下面这个是为了页面保持是已登录的状态，如果未登录那么就需要返回403；这里返回403后，前端就会以失败的响应进行响应的操作(跳转到登录状态）
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);

    }
}
